package org.yuezejian.alarm.netty.handler;

import org.yuezejian.alarm.netty.config.NettyConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理器工厂
 *
 * @author yuezejian
 * @since 2024.8.1
 */
@Component
@Slf4j
public class ClientHandlerFactory {
    private final Map<String, String> handlerMap = new HashMap<>();

    @Autowired
    public ClientHandlerFactory(NettyConfig nettyConfig) {
        for (NettyConfig.HandlerConfig config : nettyConfig.getHandlers()) {
            handlerMap.put(config.getType(), config.getName()); // 维护类型与 Bean 名称的映射
        }
        log.info("ClientHandlerFactory inited with handlerMap: " + handlerMap.toString());
    }

    @Autowired
    private ApplicationContext applicationContext;

    public AbstractClientHandler createHandler(String type) {
        String beanName = handlerMap.get(type);
        if (beanName != null) {
            return (AbstractClientHandler) applicationContext.getBean(beanName);
        } else {
            throw new IllegalArgumentException("No handler found for type: " + type);
        }
    }
}
